package com.pucong.gitee.database.backup.business.database.util;

import com.pucong.gitee.database.backup.business.database.dto.OperateFunctionDto;
import com.pucong.gitee.database.backup.business.database.mapper.AutoExeSqlLogMapper;
import com.pucong.gitee.database.backup.common.entity.database.AutoDataSource;
import com.pucong.gitee.database.backup.common.selfenum.DatabaseTypeEnum;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

import static com.pucong.gitee.database.backup.common.selfenum.DatabaseTypeEnum.*;

@Service
public class BackupServiceFactory {

    private final Map<DatabaseTypeEnum, Function<OperateFunctionDto, OperationService>> operateFunctionMap = new HashMap<>();

    /**
     * 工厂生产sql执行器
     * @param autoDataSource
     * @param autoExeSqlLogMapper
     * @return
     */
    public OperationService getBackupService(AutoDataSource autoDataSource, AutoExeSqlLogMapper autoExeSqlLogMapper) {
        OperateFunctionDto operateFunctionDto = new OperateFunctionDto(autoDataSource, autoExeSqlLogMapper);
        Function<OperateFunctionDto, OperationService> serviceFunction = operateFunctionMap.get(autoDataSource.getDatabaseType());
        return serviceFunction.apply(operateFunctionDto);
    }

    @PostConstruct
    public void initOperateFunctionMap() {
        operateFunctionMap.put(oracle, param -> new OperationServiceOracleImpl(param.getAutoDataSource(), param.getAutoExeSqlLogMapper()));
        operateFunctionMap.put(mysql, param -> new OperationServiceMysqlImpl(param.getAutoDataSource(), param.getAutoExeSqlLogMapper()));
        operateFunctionMap.put(postgresql, param -> new OperationServicePgsqlImpl(param.getAutoDataSource(), param.getAutoExeSqlLogMapper()));
        operateFunctionMap.put(sqlserver, param -> new OperationServiceMssqlImpl(param.getAutoDataSource(), param.getAutoExeSqlLogMapper()));
        operateFunctionMap.put(hive, param -> new OperationServiceHivelImpl(param.getAutoDataSource(), param.getAutoExeSqlLogMapper()));
    }

}